package com.common.playing.apps.comm.net;

import android.util.Log;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import internal.org.apache.http.entity.mime.HttpMultipartMode;
import internal.org.apache.http.entity.mime.MultipartEntity;

public class CustomMultipartEntity extends MultipartEntity {
	private static final String TAG = CustomMultipartEntity.class.getSimpleName();
	private final ProgressListener listener;
	private boolean mIsPaused = false;

	public CustomMultipartEntity(final ProgressListener listener) {
		super();
		this.listener = listener;
	}

	public CustomMultipartEntity(final HttpMultipartMode mode,
			final ProgressListener listener) {
		super(mode);
		this.listener = listener;
	}

	public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,
			final Charset charset, final ProgressListener listener) {
		super(mode, boundary, charset);
		this.listener = listener;
	}
	
	public void setIsPaused(boolean isPaused) {
		Log.e(TAG, "setIsPaused : " + isPaused);
		mIsPaused = isPaused;
	}

	public boolean transferred(long num, long total) {
		if (null != this.listener) {
			this.listener.transferred(num, total);
		}
		return !mIsPaused;
	}
	
	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		super.writeTo(new CountingOutputStream(outstream, this.listener));
	}

	public static interface ProgressListener {
		void transferred(long num, long total);
	}

	public static class CountingOutputStream extends FilterOutputStream {
		
		private final ProgressListener listener;
		private long transferred;

		public CountingOutputStream(final OutputStream out,
				final ProgressListener listener) {
			super(out);
			this.listener = listener;
			this.transferred = 0;
		}

		public void write(byte[] b, int off, int len) throws IOException {
//			if (sIsPaused) {
//				Log.e(TAG, "write paused");
//				throw new IOException("upload paused");
//			}
			out.write(b, off, len);
			this.transferred += len;
			this.listener.transferred(this.transferred, 0);
		}

		public void write(int b) throws IOException {
			out.write(b);
			this.transferred++;
			this.listener.transferred(this.transferred, 0);
		}
	}
}
